import CryptoJS from 'crypto-js'
const CRYPTO_USER_KEY = 'bd3f1a69f8c14bd7'
const CRYPTO_ORDER_KEY = '2f0abd8000de8ec3'
// 获取url参数
export const GetQueryString = name => {
  var url = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
  var newUrl = window.location.search.substr(1).match(url)
  if (newUrl != null) {
    return unescape(newUrl[2])
  } else {
    return false
  }
}
// 对象序列号
export const GetParamString = param => {
  var parameters = '?'
  for (var key in param) {
    parameters += key + '=' + param[key] + '&'
  }
  parameters = parameters.substr(0, parameters.length - 1)
  // 编码因为paramMap={"type":""}的{}在liunx无法使用
  parameters = encodeURI(parameters)
  return parameters
}

// 获取到顶部的距离 有loadmore的不能直接window
export function getScrollTop() {
  const element = document.getElementById('loadmore')
  if (element) {
    return element.scrollTop
  } else {
    return Math.max(window.pageYOffset || 0, document.documentElement.scrollTop)
  }
}
// 设置距离 有loadmore的不能直接window
export function setScrollTop(value) {
  const element = document.getElementById('loadmore')

  if (element) {
    element.scrollTop = value
    element.scrollTo(0, value)
  } else {
    window.scrollTop = value
    window.scrollTo(0, value)
  }
}
/*
  * {param} plaintText 加密明文
  * {param} type 加密类型 0 用户密码加密，1订单加密
  * return  str 加密结果
  */

export const encryptString = (plaintext, type) => {
  var plaintText = plaintext
  var options = {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  }
  var cryptojskey = type === 1 ? CRYPTO_ORDER_KEY : CRYPTO_USER_KEY
  var key = CryptoJS.enc.Utf8.parse(cryptojskey)
  var encryptedData = CryptoJS.AES.encrypt(plaintText, key, options)
  var encryptedBase64Str = encryptedData.toString()
  return encryptedBase64Str
}

/*
  * {param} plaintText 解密密文
  * {param} type 解密类型 0 用户密码解密，1 订单解密
  * return  str 解密结果
  */

export const decryptString = (encryptedStr, type) => {
  var encryptedBase64Str = encryptedStr
  var options = {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  }
  var cryptojskey = type === 1 ? CRYPTO_ORDER_KEY : CRYPTO_USER_KEY
  var key = CryptoJS.enc.Utf8.parse(cryptojskey)
  // 解密
  var decryptedData = CryptoJS.AES.decrypt(encryptedBase64Str, key, options)
  // 解密后，需要按照Utf8的方式将明文转位字符串
  var decryptedStr = decryptedData.toString(CryptoJS.enc.Utf8)
  return decryptedStr
}
export const setLocalStorage = (key, value) => {
  if (!key) return
  let val = value
  if (typeof value !== 'string') {
    val = JSON.stringify(value)
  }
  window.localStorage.setItem(key, val)
}

export const getLocalStorage = key => {
  if (!key) return
  return window.localStorage.getItem(key)
}

export const removeLocalStorage = key => {
  if (!key) return
  window.localStorage.removeItem(key)
}

export const setSessionStorage = (key, value) => {
  if (!key) return
  let val = value
  if (typeof value !== 'string') {
    val = JSON.stringify(value)
  }
  window.sessionStorage.setItem(key, val)
}

export const getSessionStorage = key => {
  if (!key) return
  return window.sessionStorage.getItem(key)
}

export const removeSessionStorage = key => {
  if (!key) return
  window.sessionStorage.removeItem(key)
}

export const search = key => {
  if (!key) return
  var reg = new RegExp('(^|&)' + key + '=([^&]*)(&|$)')
  var url =
    window.location.hash === ''
      ? window.location.search
      : window.location.hash.substring(window.location.hash.indexOf('?'))
  var r = url.substr(1).match(reg)
  if (r != null) return unescape(r[2])
  return null
}

/**
 * 显示返回顶部按钮，开始、结束、运动 三个过程中调用函数判断是否达到目标点
 */
export const showBack = callback => {
  let requestFram
  let oldScrollTop

  document.addEventListener(
    'scroll',
    () => {
      showBackFun()
    },
    false
  )
  document.addEventListener(
    'touchstart',
    () => {
      showBackFun()
    },
    { passive: true }
  )

  document.addEventListener(
    'touchmove',
    () => {
      showBackFun()
    },
    { passive: true }
  )

  document.addEventListener(
    'touchend',
    () => {
      oldScrollTop =
        document.body.scrollTop | document.documentElement.scrollTop
      moveEnd()
    },
    { passive: true }
  )

  const moveEnd = () => {
    requestFram = requestAnimationFrame(() => {
      if (
        document.body.scrollTop |
        (document.documentElement.scrollTop !== oldScrollTop)
      ) {
        oldScrollTop =
          document.body.scrollTop | document.documentElement.scrollTop
        moveEnd()
      } else {
        cancelAnimationFrame(requestFram)
      }
      showBackFun()
    })
  }

  // 判断是否达到目标点
  const showBackFun = () => {
    if (document.body.scrollTop | (document.documentElement.scrollTop > 500)) {
      callback(true)
    } else {
      callback(false)
    }
  }
}
